import wiringpi as gpio
from digit_tube import numbers

ds = 11
stcp = 12
shcp = 13

gpio.wiringPiSetupPhys()
gpio.pinMode(ds, gpio.OUTPUT)
gpio.pinMode(stcp, gpio.OUTPUT)
gpio.pinMode(shcp, gpio.OUTPUT)

gpio.digitalWrite(stcp, gpio.LOW)
gpio.digitalWrite(shcp, gpio.LOW)

def set_bit_data(data):
	gpio.digitalWrite(ds, data)
	gpio.digitalWrite(shcp, gpio.LOW)
	gpio.digitalWrite(shcp, gpio.HIGH)

def show_digit(n, dp):
	for d in numbers[str(n)][::-1]:
		set_bit_data(abs(int(d)-1))
	if dp:
		set_bit_data(0)
	else:
		set_bit_data(1)
	gpio.digitalWrite(stcp, gpio.HIGH)
	gpio.digitalWrite(stcp, gpio.LOW)

def select_position(position: tuple):
	for i in position:
		set_bit_data(int(i))

def clear():
	for d in range(8):
		set_bit_data(0)
	for d in range(8):
		set_bit_data(1)
	gpio.digitalWrite(stcp, gpio.HIGH)
	gpio.digitalWrite(stcp, gpio.LOW)

if __name__ == '__main__':
	clear()
	while True:
		s = gpio.micros()
		num = '169.2'
		dpi = num.index('.') - 1
		num = num.replace('.', '')
		for i, n in enumerate(num):
			dp = dpi == i
			position = '1' + ('0'*(i))
			position = tuple('0'*(8-len(position)) + position)
			select_position(position)
			show_digit(n, dp)
			gpio.delay(3)
			clear()
		print(gpio.micros()-s)
			
			
